package com.du.cloud.oauth.config;

import com.du.cloud.oauth.model.User;
import com.du.cloud.oauth.model.info.UserDetail;
import com.du.cloud.oauth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Desc:
 * Author: dushuang
 * Date 2019/12/30 16:00
 */
@Service(value = "userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 数据库查询user
        User user = userService.getUserByName(username);
        if (user != null) {
            if (user.getFlag() == 0) {
                throw new DisabledException("账号已禁用!");
            }
            Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
            // 权限
            List<String> rules = userService.getUserAuthorization(user.getId());
            rules.forEach(i -> grantedAuthorities.add(new SimpleGrantedAuthority(i)));

            return new UserDetail(user, grantedAuthorities);
        } else {
            throw new UsernameNotFoundException("username or password error!");
        }
    }
}
